#include <stdio.h>
#include <windows.h>

#include "config.h"
#include "event.h"
#include "util.h"
#include "serial.h"

int
main(int argc, char **argv)
{
	char *com_file;
	char *out_file;
	FILE *fp;
	struct serial_dev sdev;
	int r, total;
	char buf[128];
	struct config config;

	if (argc != 3) {
		fprintf(stderr, "usage: %s comN output_file\n", argv[0]);
		exit(1);
	}

	com_file = argv[1];
	out_file = argv[2];

	fp = fopen(out_file, "wb+");
	if (fp == NULL) {
		fprintf(stderr, "error: could not open %s\n", out_file);
		exit(1);
	}

	if (init_serial(&sdev, com_file) == -1)
		exit(1);

	strcpy(buf, "!!!\recho off\r");
	r = write_ser(&sdev, buf, strlen(buf));
	if (r != strlen(buf)) {
		fprintf(stderr, "error: could not write.\n");
		exit(1);
	}

	ser_flush(&sdev);
	
	strcpy(buf, "read_cfg\r");
	r = write_ser(&sdev, buf, strlen(buf));
	if (r != strlen(buf)) {
		fprintf(stderr, "error: could not write.\n");
		exit(1);
	}

	total = 0;
	while (total < sizeof(config)) {
		r = sizeof(config) - total;
		if (r > sizeof(buf))
			r = sizeof(buf);

	 	r = read_ser(&sdev, buf, r);
		if (r == 0) {
			fprintf(stderr, "error: could not read.\n");
			exit(1);
		} else {
			memcpy(&config + total, buf, r);
#if 0
			fwrite(buf, 1, r, fp);
			printf("wrote %d bytes\n", r);
#endif
			total += r;
		}
	}

	if (!valid_config(&config)) {
		fprintf(stderr, "error: invalid config read.\n");
		exit(1);
	} else {
		r = fwrite(&config, 1, sizeof(config), fp);
		printf("Read good config.\n");
	}

	close_serial(&sdev);

	fclose(fp);

	return 0;
}
